﻿using System.Collections.Generic;
using System.Linq;

namespace StudentAI
{
    public class PriQueue
    {
        private LinkedList<Node> queue;

        public PriQueue()
        {
            queue = new LinkedList<Node>();
        }

        public int Count()
        {
            return queue.Count;
        }

        public void Swap(Node nodeInList, Node swapNode)
        {
            queue.AddAfter(queue.Find(nodeInList), new LinkedListNode<Node>(swapNode));
            queue.Remove(nodeInList);
        }

        public Node Find(Node node)
        {
            return queue.FirstOrDefault(n => n.Move == node.Move);
        }

        public Node Pop()
        {
            if (queue.Count > 0)
            {
                Node first = queue.First.Value;
                queue.RemoveFirst();
                return first;
            }
            return null;
        }

        public void Apppend(Node node)
        {
            if (queue.Count == 0)
            {
                queue.AddFirst(node);

            }
            else if (queue.Count == 1)
            {
                if(queue.First.Value.Priority > node.Priority)
                {
                    queue.AddAfter(queue.First, node);
                }
                else
                {
                    queue.AddFirst(node);
                }
            }
            else
            {
                bool added = false;
                var listNode = queue.First;
                while (listNode.Next != null)
                {
                    if (node.Priority >= listNode.Value.Priority)
                    {
                        queue.AddBefore(listNode, new LinkedListNode<Node>(node));
                        added = true;
                        break;
                    }
                    listNode = listNode.Next;
                }
                if (!added)
                {
                    queue.AddLast(node);
                }
            }
        }
    }
}
